home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5486 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: problems reading binary data from file
  5. Date: Mon, 05 Feb 1996 12:58:41 GMT
  6. Organization: Netcom
  7. Message-ID: <3115fd64.299425728@nntp.ix.netcom.com>
  8. References: <4f4c4s$69q@zeus.rbi.informatik.uni-frankfurt.de>
  9. NNTP-Posting-Host: ix-dc7-16.ix.netcom.com
  10. X-NETCOM-Date: Mon Feb 05  4:57:50 AM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. Ferber@zoology.uni-frankfurt.de (Michael Ferber) wrote:
  14.  
  15. > I have to read/write binary data from/to a file. Up to now I did this with
  16. > fread and fwrite, but I want to switch to the fstream classes to avoid mixture
  17. > of c and c++ code. Unfortunately the following code (the first part which 
  18. > writes to temp.bin) writes characters not binaries. What am I doing wrong???
  19. > The second part (which writes to test.bin) works as expected. I use Watcom 
  20. > 10.0a. The code is a modiffied piece of the Watcom samples provided with the 
  21. > compiler. 
  22. > Thanks in advance
  23. > Michael
  24. > #include <fstream.h>
  25. > #include <sys\stat.h>
  26. > #include <sys\types.h>
  27. > #include <fcntl.h>
  28. > #include <stdio.h>
  29. > void main( void ) 
  30. > {
  31. >     int     handle;
  32. >     handle = open( "temp.bin", ios::binary | ios::out , S_IRWXU );
  33. >     fstream    test ( handle );
  34. >     for(int k = 1; k <=1000; k++)
  35. >     test << k;
  36. >     FILE *test2;
  37. >     test2 = fopen("test.bin", "w+b");
  38. >     for(int m = 1; m <=1000; m++)
  39. >         fwrite(&m, sizeof(m),1,    test2);
  40. > }
  41.  
  42. You're using the wrong operator to write out the data.  << writes to
  43. the stream using the text representation of the data even if the
  44. stream is binary.  You want something like
  45.  
  46.     test.write((char*) &k, sizeof k);
  47.  
  48.  
  49. Michael M Rubenstein
  50.